import { Link } from 'react-router-dom'
import { useAppSelector } from '../../../../hooks'
import { selectUser } from '../../../../store/reducers/selectors'
import { useEffect, useState } from 'react'
import FavoriteBorderIcon from '@mui/icons-material/FavoriteBorder'
import { Badge, CircularProgress } from '@mui/material'
import { useGetAllProductsQuery } from '../../../../api/productsApiSlice'
import { useSkipAccessToken } from '../../../../hooks/useSkipAccessToken'

export const FAVORITES_BUTTON_TEST_ID = 'FAVORITES_BUTTON_TEST_ID'

const FavoritesButton = () => {
	const user = useAppSelector(selectUser)

	const { data, isLoading } = useGetAllProductsQuery(
		undefined as never,
		useSkipAccessToken()
	)

	const [favorites, setFavorites] = useState(0)

	useEffect(() => {
		if (!user) {
			setFavorites(0)
		} else {
			const count =
				data?.allProducts?.filter((product) =>
					product.likes.includes(user?._id)
				).length || 0
			setFavorites(count)
		}
	}, [data?.allProducts, user])

	return (
		<>
			{isLoading ? (
				<CircularProgress />
			) : (
				<Link to={'favorites'}>
					<Badge
						badgeContent={favorites}
						data-testid={FAVORITES_BUTTON_TEST_ID}
					>
						<FavoriteBorderIcon />
					</Badge>
				</Link>
			)}
		</>
	)
}

export default FavoritesButton
